import json
import grpc
import consul
from goods_srv.proto import goods_pb2_grpc, goods_pb2
from goods_srv.settings import settings
from google.protobuf import empty_pb2


class GoodsTest:
    def __init__(self):
        # 连接grpc服务器
        c = consul.Consul(host="192.168.10.130", port=8500)
        services = c.agent.services()
        ip = ""
        port = ""
        for key, value in services.items():
            if value["Service"] == settings.SERVICE_NAME:
                ip = value["Address"]
                port = value["Port"]
                break
        if not ip:
            raise Exception()

        channel = grpc.insecure_channel(f"{ip}:{port}")
        self.goods_stub = goods_pb2_grpc.GoodsStub(channel)

    def goods_list(self):
        rsp: goods_pb2.GoodsListResponse = self.goods_stub.GoodsList(
            goods_pb2.GoodsFilterRequest(topCategory=130358)
        )
        for item in rsp.data:
            print(item.name, item.shopPrice)

    def batch_get(self):
        ids = [421, 422]
        rsp: goods_pb2.GoodsListResponse = self.goods_stub.BatchGetGoods(
            goods_pb2.BatchGoodsIdInfo(id=ids)
        )
        for item in rsp.data:
            print(item.name, item.shopPrice)

    def get_detail(self, id):
        rsp: goods_pb2.GoodsInfoResponse = self.goods_stub.GetGoodsDetail(
            goods_pb2.GoodInfoRequest(id=id)
        )
        print(rsp.name, rsp.shopPrice)

    def create_good(self):
        rsp: goods_pb2.GoodsInfoResponse = self.goods_stub.CreateGoods(
            goods_pb2.CreateGoodsInfo(
                categoryId=136982,
                brandId=614,
                name="奥里给",
                goodsSn="",
                marketPrice=1.1,
                shopPrice=1.1,
                goodsBrief="我奥里给那",
                shipFree=True,
                images="http://awsl.jpg",
                descImages="http://awsl.jpg",
                goodsFrontImage="",
                isNew=True,
                isHot=True,
                onSale=True
            )
        )
        print(rsp.name)

    def delete_good(self):
        rsp: empty_pb2.Empty = self.goods_stub.DeleteGoods(
            goods_pb2.DeleteGoodsInfo(id=841)
        )
        print(rsp)

    def category(self):
        rsp: empty_pb2.Empty = self.goods_stub.GetAllCategorysList(
            empty_pb2.Empty()
        )
        data=json.loads(rsp.jsonData)
        print(data)


if __name__ == '__main__':
    goods = GoodsTest()
    # goods.goods_list()
    # goods.batch_get()
    # goods.get_detail(421)
    # goods.create_good()
    # goods.delete_good()
    goods.category()
